package com.ybkj.daijia.server.event.listener.errand;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.server.errand.Order;
import com.ybkj.daijia.server.event.model.DriverPowerOfflineEvent;
import com.ybkj.daijia.server.event.model.errand.PaotuiOrderUpFinishEvent;
import com.ybkj.daijia.server.mapper.MemberNoticeMapper;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SmsTempletService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class PaotuiOrderUpFinishEventListener implements
    ApplicationListener<PaotuiOrderUpFinishEvent> {

    private static final Logger logger = LoggerFactory
        .getLogger(PaotuiOrderUpFinishEventListener.class);

    @Autowired
    private SmsTempletService smsTempletService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private MemberNoticeMapper memberNoticeMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Override
    @Async
    public void onApplicationEvent(PaotuiOrderUpFinishEvent event) {

        logger.debug("order paotui finish event:{}", "");

        Order order = (Order) event.getSource();

        Driver driver = driverService.findOne(order.getEmployId());

        //发送短信
        String payway = order.getPreAndAfterPayType();

        Company orderCompany = companyService.findOne(order.getCompanyId());

        Company maincompany = companyService.getMain();
        Setting setting = settingUtils.get();
        Company finalCompany = orderCompany;
        if (!orderCompany.equals(maincompany.getId()) && setting.isSmsMainCompany()) {
            finalCompany = maincompany;
        }
        if (setting.getWhichServicePhone() == 1) {
            maincompany = orderCompany;
        }

        try {
            SmsTemplet templet = smsService
                .findByAlias(finalCompany.getId(), SmsType.orderFinished);
            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                //smsService.sendSms(order.getPassengerPhone(), "finishPaotuiOrder", "{\"订单号\":\""+"***"+order.getOrderNo().substring(4)+"\",\"服务人员工号\":\""+driver.getUsername()+"\",\"等候时间\":\""+order.getWaitedTime()+""+"\",\"行驶公里\":\""+order.getMileage()+""+"\",\"收费金额\":\""+order.getRealPay().toString()+"\",\"支付方式\":\""+payway+"\",\"投诉建议电话\":\""+finalCompany.getTelephone()+"\"}", finalCompany.getId(), 0, finalCompany.getSignName());
                //短信发送（改）
                JSONObject smsParam = new JSONObject();
                smsParam.put("order", order.getOrderNo().substring(4));
                smsParam.put("driver", driver.getUsername());
                smsParam.put("waitTime", order.getWaitedTime());
                smsParam.put("mileage", order.getMileage());
                smsParam.put("realCash", order.getRealPay().toString());
                smsParam.put("payWay", payway);
                smsParam.put("tel", finalCompany.getTelephone());
                smsService.sendSms(order.getPassengerPhone(), templet.getTemplateId(),
                    smsParam.toJSONString(), finalCompany.getId(), 0, finalCompany.getSignName());
            }
        } catch (Exception e) {
            logger.error("发送短信发生异常：{}", e.getMessage());
        }

        //司机最低上班余额
        if (driver.getStatus().equals(Driver.DRIVER_ONLINE)
            && driver.getType().equals(Driver.DRIVER_TYPR_PARTTIME)
            && setting.getLowestWorkVirtual() != 0
            && driver.getVirtual().doubleValue() < setting.getLowestWorkVirtual()) {

            driver.setStatus(Driver.DRIVER_OFFLINE);
            driverService.updateStatus(Driver.DRIVER_OFFLINE, driver.getId());

            DriverPowerOfflineEvent driverPowerOfflineEvent = new DriverPowerOfflineEvent(driver,
                Driver.DRIVER_ONLINE, "sys");
            applicationEventMulticaster.multicastEvent(driverPowerOfflineEvent);

        }

    }

}
